﻿uart: 0;
currentData = 0;
audio = pm.createAudioContext();
fmData = 0;             //接收JSON数据
weatherInfo = 0;
currentCity = { name: "大连", location: "121.53,38.88" };
mqttClient = 0;         //MQTT客户端
main_Setting_page = 0;  //页面Page的编号
dateTimer = 0;          //wifi信号质量定时器

//HTTP 请求获取天气数据
getFeatureWeather = function (isRefresh, func) {
    pm.request({
        // 获取天气预报的API，返回数据
        url: 'http://api.caiyunapp.com/v2/atUin4udo8zdEVMj/' + currentCity.location + '/forecast.json',
        method: 'GET',
        header: {
            "Content-Type": "application/json"
        },
        //连接成功后，执行的回调函数
        success: function (res) {
            if (weatherInfo != 0 && isRefresh == false) {
                return;
            }
            // 把data从Buffer转成string
            var str = res.data.toString('utf8');
            //把JSON格式的string转成JSON对象，以便获取数据   
            var json_obj = JSON.parse(str);
            weatherInfo = new Object();
            weatherInfo.hourly = new Object();
            // 获取到温度
            weatherInfo.hourly.Temperature = json_obj.result.hourly.temperature;
            // 获取到天气情况 晴/多云/阴天
            weatherInfo.hourly.Skycon = json_obj.result.hourly.skycon;
            // 湿度
            weatherInfo.hourly.Humidity = json_obj.result.hourly.humidity;
            weatherInfo.daily = new Object();
            weatherInfo.daily.Temperature = json_obj.result.daily.temperature;
            weatherInfo.daily.Skycon = json_obj.result.daily.skycon;

            if (typeof (func) == "function") {
                func();                                 // @@@@这里回调的是weather中定义的函数！！
                console.log('@@  function ==》 func request success    _app.js');
            }
            console.log('@@getFeatureWeather request success  _app.js')
        },
        fail: function () {
            console.log('@@getFeatureWeather request failed   _app.js')
        },
    });
}

/*通过http 获取专辑信息*/
getAblum = function () {
    var that = this;
    var rq = pm.request({
        url: "http://www.rt-thread.com/PersiomM/fm/",
        header: {
            "Content-Type": "application/json"
        },
        success: function (res) {
            console.log('@@----getAblum request success   _app.js');
            if (fmData != 0) {
                return;
            }
            fmData = JSON.parse(res.data);
        },
        fail: function () {
            console.log('@@----getAblum request failed    _app.js');
        }
    });
}

var wifi = { module: 0, enable: true, isConnected: false, strength: "none", connect_timer: 0, current_ap: 0 };
var roomInfo = [
    { name: "bedroom", label: "卧室", temperature: 20, humidity: 52, PPM: 35 },
]

//全局函数--每隔一段时间获取一次wifi信号质量--展示
refreshDate = function (page) {
    page.setData({ wifiImg: { value: "wifi_" + wifi.strength + ".png" } });
    page.dateTimer = setInterval(function () {
        page.setData({ wifiImg: { value: "wifi_" + wifi.strength + ".png" } });
    }, 1000 * 1)
}

var app = {
    page: "main/main",
    httpInfoTimer: 0,   //HTTP GET 定时器

    /* app 加载完成触发该函数 */
    onLaunch: function () {
        var that = this;

        /***********************************************************USART***********************************************************/
        uart = pm.openSerialPort({ port: "uart0", baud: 115200 });

        //串口0接收数据函数
        uart.onData(function (data) {
            console.log('uart data : ' + data.toString('ascii'));
            console.log('data length : ' + data.length);
            //定义全局对象 设置全局的接收回调函数 指定到当前页面
            if (currentData)
                currentData.uartUpdate(data.toString('ascii'));
        });
        /***********************************************************WIFI***********************************************************/
        //实例化wifi对象
        wifi.module = pm.createWifi();

        //扫描成功的回调函数 onScanEvent
        wifi.module.onScanEvent(function (res) {
            if (res && main_Setting_page != 0) {
                console.log("@@@======================WiFi scanned success=======================   #app.js");
                if (wifi.enable && wifi.isConnected) {
                    //main_Setting_page.setData({ WifiPrompt: { value: "WiFi — \"" + wifi.module.getConnected().ssid + "\" 已连接" } });
                    console.log("已连接")
                }

                wifiArray = new Array();
                main_Setting_page.wifiApArray = new Array();
                for (var i = 0; i < res.length; i++) {
                    var item = res[i];
                    if (item.ssid != "") {
                        main_Setting_page.wifiApArray.push(item);
                        var wifiItem = new Object();
                        wifiItem.wifi_ssid = new Object();
                        wifiItem.wifi_ssid.value = item.ssid;
                        wifiItem.wifi_ssid.id = "wifi_button" + i;
                        wifiItem.panel1 = new Object();
                        wifiItem.panel1.id = "wifi_panel" + i;
                        wifiItem.wifi_strength = new Object();

                        var strength = parseInt(item.strength / 20);
                        if (strength > -2) {
                            wifiItem.wifi_strength.value = "wifi_strong.png";
                        } else if (strength > -4) {
                            wifiItem.wifi_strength.value = "wifi_middle.png";
                        } else {
                            wifiItem.wifi_strength.value = "wifi_week.png";
                        }
                        if (item.secure) {
                            wifiItem.wifi_security = new Object();
                            wifiItem.wifi_security.value = "wifi_security.png"
                        }

                        if (wifi.isConnected && item.ssid == wifi.module.getConnected().ssid && item.bssid == wifi.module.getConnected().bssid) {
                            wifiItem.wifi_isConnected = new Object();
                            wifiItem.wifi_isConnected.value = "wifi_tick.png";
                        }

                        wifiArray.push(wifiItem);
                    }
                }
                if (main_Setting_page.wifiPanel_isShown) {
                    //console.log(wifiArray)
                    main_Setting_page.setData({ wifi_list: { list: { page: main_Setting_page, items: [{ xml: "Panels/WifiItem", items: wifiArray }] } } });
                }
            }
            else {
                console.log("WiFi cannot be scanned.");
            }
        });

        /****获取最近连接的wifi ssid， bssid & password，并尝试连接****/
        var current_wifi_info = pm.getStorageSync('current_wifi_info');

        //定时器每4s尝试连接网络
        wifi.connect_timer = setInterval(function () {
            console.log("=====> try to connect wifi......  app.js");
            if (current_wifi_info) {
                console.log("current_wifi_info==>" + current_wifi_info.ssid + " " + current_wifi_info.bssid + " " + current_wifi_info.psd);

                if (wifi.isConnected) {
                    wifi.module.disconnect();
                }
                wifi.module.connect({
                    ssid: current_wifi_info.ssid,
                    bssid: current_wifi_info.bssid,
                    password: current_wifi_info.psd
                })
            }
        }, 4 * 1000)

        //监听连接事件，回调onConnectEvent判断连接结果
        wifi.module.onConnectEvent(function (res) {
            if (res) {
                if (main_Setting_page != 0) {
                    main_Setting_page.setData({ WifiPrompt: { value: "WiFi — \"" + wifi.module.getConnected().ssid + "\" 开始连接" } });
                }
            } else {
                audio.stop();
                if (this.client != 0) {
                    this.client.end(function () {
                        console.log("mqttClient  >> end")
                    });
                }
                if (wifi != 0) {
                    main_Setting_page.setData({ WifiPrompt: { value: "WiFi — 连接失败" } });
                    wifi.module.scan();
                }
            }
        });

        //监听连接网络，回调onNetworkEvent判断连接结果，当返回为true ，则连接网络成功。
        wifi.module.onNetworkEvent(function (res) {
            wifi.isConnected = res;
            if (res) {
                var strength = parseInt(wifi.module.getConnected().strength / 20);  //获取信号质量
                if (strength > -2) {
                    wifi.strength = "strong";
                } else if (strength > -4) {
                    wifi.strength = "middle";
                } else {
                    wifi.strength = "week";
                }

                if (wifi.connect_timer != 0) {
                    clearInterval(wifi.connect_timer);
                    wifi.connect_timer = 0;
                }

                if (main_Setting_page != 0) {
                    if (wifi.isConnected) {
                        main_Setting_page.setData({ WifiPrompt: { value: "WiFi — \"" + wifi.module.getConnected().ssid + "\" 已连接" } });
                    }
                    wifi.module.scan();
                }

                if (!current_wifi_info) {
                    /***************存储wifi的名称号码***************/
                    console.log("@@ Wifi is not excess now try to storage password....   #app.js")
                    pm.setStorageSync('current_wifi_info', wifi.current_ap);
                    pm.setStorageSync('current_wifi_ssid', wifi.current_ap.ssid);
                    pm.setStorageSync('current_wifi_bssid', wifi.current_ap.bssid);
                    pm.setStorageSync('current_wifi_psd', wifi.current_ap.psd);
                }

                /****************************************************HTTP******************************************************* */
                //HTTP 定时器
                that.httpInfoTimer = setInterval(function () {
                    console.log("@@@=================> httpInfoTimer is request   #app.js");
                    if (weatherInfo != 0) {
                        console.log("@@ httpInfoTimer is clear   #app.js");
                        clearInterval(that.httpInfoTimer);
                        that.httpInfoTimer = 0;
                    }

                    if (fmData == 0) {
                        getAblum();/*通过http 获取专辑信息*/
                    }

                    if (weatherInfo == 0) {
                        getFeatureWeather(false, 0);    //没有获取到天气再次发出GET请求天气数据 --- 定时请求 3s
                    }
                }, 3 * 1000)
                console.log("Network is connected");

                /******************************************************mqtt--待测试--需要用emq服务器***************************************************** */

                // if (mqttClient == 0) {
                //     var mqttModule = require("mqtt");
                //     mqttClient = mqttModule.Client("tcp://101.201.68.150：1883");
                //     mqttClient.subscribe("v1/devices/me/telemetry", { qos: 0 }, function () {
                //         console.log("subcribe topic success")
                //     });
                //     //绑定message事件的Listener --- 监听MQTT订阅的消息回调函数，当接收到订阅的消息，则打印出来
                //     mqttClient.on("message", function (topic, message) {
                //         if (topic == "v1/devices/me/telemetry") {
                //             var setValue = JSON.parse(message.toString());
                //             if (typeof (setValue) != "object") {
                //                 return;
                //             }
                //             for (var i = 0, len = roomInfo.length; i < len; i++) {
                //                 if (typeof (setValue.name) == "string" && setValue.name == roomInfo[i].name) {
                //                     if (typeof (setValue.temperature) == "number") {
                //                         roomInfo[i].temperature = setValue.temperature;
                //                     }
                //                     if (typeof (setValue.humidity) == "number") {
                //                         roomInfo[i].humidity = setValue.humidity;
                //                     }
                //                     if (typeof (setValue.temperature) == "number") {
                //                         roomInfo[i].temperature = setValue.temperature;
                //                     }
                //                     console.dir(roomInfo[i]);
                //                     that.onUpdate({ value: "Update_mqttdata" });
                //                 }
                //             }
                //         }
                //     })
                //     mqttClient.connect();   //建立mqtt连接
                // } else {
                //     mqttClient.reconnect(); //mqtt重连
                // }
            }
        });
    },

    /* app 退出触发该函数 */
    onExit: function () {
        if (wifi.connect_timer != 0) {
            clearInterval(wifi.connect_timer);
        }

        if (wifi.connect_timer != 0) {
            clearInterval(wifi.connect_timer);
        }

        if (this.httpInfoTimer != 0) {
            clearInterval(this.httpInfoTimer);
        }

        if (dateTimer != 0) {
            clearInterval(dateTimer);
        }

        this.client.end(function () {
            console.log("mqtt end")
        });

        this.client = 0; //关闭mqtt客户端
        wifi.module.disconnect();
        wifi.module.destroy();
        audio.destroy();
    },
};

App(app);

app = 0;
